package com.qxzn.module.im.activity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.view.ArrowRefreshHeader;
import com.qxzn.app.api.greendao.SQLiteDbUtil;
import com.qxzn.app.api.greendao.bean.ChatMsgBean;
import com.qxzn.app.api.greendao.bean.ChatMsgBeanDao;
import com.qxzn.app.api.greendao.bean.DaoSession;
import com.qxzn.app.bean.BaseBean;
import com.qxzn.app.bean.EventBusBean;
import com.qxzn.app.bean.MsgBean;
import com.qxzn.app.bean.SendMsgSuccessBean;
import com.qxzn.app.page.BaseActivity;
import com.qxzn.app.page.util.PermissionUtil;
import com.qxzn.app.page.util.face.FileUtil;
import com.qxzn.app.page.view.MyDialog;
import com.qxzn.app.page.view.VoicePickerView;
import com.qxzn.app.util.AppUtil;
import com.qxzn.app.util.CommonUtil;
import com.qxzn.app.util.Constant;
import com.qxzn.app.util.DateUtil;
import com.qxzn.app.util.SharePreferenceUtil;
import com.qxzn.module.im.R;
import com.qxzn.module.im.R2;
import com.qxzn.module.im.adapter.MsgListAdapter;
import com.qxzn.module.im.interfaces.MsgInterface;
import com.qxzn.module.im.model.MsgModel;
import com.tbruyelle.rxpermissions2.Permission;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import io.reactivex.functions.Consumer;

/**
 * 语音聊天页面
 */
public class ChatActivity extends BaseActivity {

    @BindView(R2.id.lrv_chat)
    LRecyclerView lrvChat;
    @BindView(R2.id.tv_leave_msg)
    TextView tvLeaveMsg;
    @BindView(R2.id.voice_picker)
    VoicePickerView voicePicker;
    private MsgListAdapter msgListAdapter;
    private LRecyclerViewAdapter recyclerViewAdapter;
    private static final int pageSize = 10;
    private int page;
    private MsgModel model;
    private MyDialog dialog;
    List<ChatMsgBean> dataList = new ArrayList<>();
    private ChatMsgBeanDao msgDao;
    private String receiver;
    private long insertId;
    private String username;

    @Override
    protected int initLayout() {
        return R.layout.activity_chat;
    }

    @Override
    protected void initView() {
        init();
        tvLeaveMsg.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
//                v.getParent().requestDisallowInterceptTouchEvent(true);
                voicePicker.onPressToSpeakBtnTouch(v, event, new VoicePickerView.EaseVoiceRecorderCallback() {
                    @Override
                    public void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength) {
//                        voicePath = voiceFilePath;
                        AppUtil.showLog("录音完成：" + voiceFilePath + "\n" + voiceTimeLength);
                        sendMsg(voiceFilePath);
                    }
                });
                return true;
            }
        });
    }

    private void sendMsg(String voiceFilePath) {
        long length = FileUtil.getFileDuration(voiceFilePath);
        if (length > 1000) {
            AppUtil.showLog("可以发送");

            ChatMsgBean bean = new ChatMsgBean();
            long createTime = System.currentTimeMillis();
            bean.setMsgId(createTime + "");
            bean.setSender(SharePreferenceUtil.getUserName(this));
            bean.setFilePath(voiceFilePath);
            bean.setFileDuration(length / 1000f);
            bean.setCreateTime(createTime);
            bean.setMsgType(2);
            bean.setUnread(1);
            bean.setReceiver(receiver);
            bean.setDirect(0);
            bean.setSendStatus(0);
            dataList.add(bean);

            msgListAdapter.notifyItemInserted(dataList.size() - 1);
            recyclerViewAdapter.notifyDataSetChanged();
            lrvChat.scrollToPosition(dataList.size());

            insertId = msgDao.insert(bean);

            model.sendMsg(insertId, bean);
        } else {
            AppUtil.showLog("不可以发送");
            AppUtil.showToast(ChatActivity.this, "说话时间太短了");
        }
    }

    @Override
    protected void iniTitleBar() {
//        tv_title.setText(TextUtils.isEmpty(getIntent().getStringExtra("nickname")) ? "语音留言" : getIntent().getStringExtra("nickname"));
        tv_title.setText("语音留言");
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        username = SharePreferenceUtil.getUserName(this);
        receiver = getIntent().getStringExtra("receiver");
        model = new MsgModel(this);
        model.setGetMsgListListener(new MsgInterface.OnGetMsgListListener() {

            @Override
            public void onSuccess(BaseBean<MsgBean> data) {
                lrvChat.refreshComplete(pageSize);
                saveChatData(data);
            }

            @Override
            public void onFailure() {
                lrvChat.refreshComplete(pageSize);
            }
        });
        model.setGetMsgListener(new MsgInterface.OnGetMsgListener() {
            @Override
            public void onSuccess(BaseBean<MsgBean.ResultBean> data) {
                if (data != null && data.getData() != null) {
                    ChatMsgBean bean = parseMsgBean(data.getData());
                    dataList.add(bean);
                    msgListAdapter.notifyItemInserted(dataList.size() - 1);
                    recyclerViewAdapter.notifyDataSetChanged();
                    lrvChat.scrollToPosition(dataList.size());
                    msgDao.insert(bean);
                }
            }
        });
        model.setSendMsgListener(new MsgInterface.OnSendMsgListener() {
            @Override
            public void onSuccess(long id, BaseBean<SendMsgSuccessBean> baseBean) {
                ChatMsgBean bean = msgDao.load(id);
                if (baseBean != null && baseBean.getCode() == 200) {
                    if (baseBean.getData() != null) {
                        bean.setCreateTime(baseBean.getData().getCreatetime());
                        bean.setMsgId(baseBean.getData().getId());
                    }
                    bean.setSendStatus(1);
                } else {
                    bean.setSendStatus(2);
                }
                msgDao.update(bean);
                refreshItemById(id);
            }

            @Override
            public void onFailure(long id) {
                ChatMsgBean bean = msgDao.load(id);
                bean.setSendStatus(2);
                msgDao.update(bean);
                refreshItemById(id);
            }

        });
        initDb();
        getDataFromDb();
        model.getMsgList(page, 20, receiver);
    }

    private void initDb() {
        DaoSession daoSession = SQLiteDbUtil.getInstance(this).getDb();
        msgDao = daoSession.getChatMsgBeanDao();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (needRequestPermission) {
            needRequestPermission = false;
            requestPermission();
        }
    }

    @Override
    public void onEventBus(EventBusBean busBean) {
        super.onEventBus(busBean);
        if (busBean.getId() == Constant.EventBusId.REFRESH_PUSH_MSG) {
            SharePreferenceUtil.setChatMsgNum(this, 0);
            model.getMsgById(busBean.getMsg());
        }
    }

    /**
     * 动态权限请求
     */
    private void requestPermission() {
        util = PermissionUtil.getInstant().setActivity(this).requestPermission(new Consumer<Permission>() {
            @Override
            public void accept(Permission permission) throws Exception {
                AppUtil.showLog("RegisterFace3Activity.accept");
                if (permission.granted) {
                } else if (permission.shouldShowRequestPermissionRationale) {
                    requestPermission();
                } else {
                    util.showPermissionNeedDialog(new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            needRequestPermission = true;
                            AppUtil.showLog("RegisterFace3Activity.setConfirmClick");
                            // 设置你的操作事项
                            CommonUtil.gotoAppDetailIntent(ChatActivity.this);
                            dialog.dismiss();
                        }
                    }, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            needRequestPermission = false;
                            AppUtil.showLog("AutoLoginActivity.setCancelClick");
                            dialog.dismiss();
                        }
                    }, PermissionUtil.READ_EXTERNAL_STORAGE, PermissionUtil.WRITE_EXTERNAL_STORAGE, PermissionUtil.RECORD_AUDIO);
                }
            }
        }, null, PermissionUtil.READ_EXTERNAL_STORAGE, PermissionUtil.WRITE_EXTERNAL_STORAGE, PermissionUtil.RECORD_AUDIO);
    }

    private void saveChatData(BaseBean<MsgBean> data) {
        if (data != null && data.getData() != null && data.getData().getResult() != null) {
            List<MsgBean.ResultBean> list = data.getData().getResult();
            List<ChatMsgBean> list1 = new ArrayList<>();
            for (MsgBean.ResultBean resultBean : list) {
                list1.add(parseMsgBean(resultBean));
            }
            msgDao.insertOrReplaceInTx(list1);//保存到本地
            getDataFromDb();
        }
    }

    private ChatMsgBean parseMsgBean(MsgBean.ResultBean resultBean) {
        ChatMsgBean bean = new ChatMsgBean();
        bean.setMsgId(resultBean.getId());
        bean.setSender(resultBean.getUsername());
        bean.setContent(resultBean.getWords());
        bean.setFileUrl(resultBean.getMessage());
        bean.setFileDuration(resultBean.getTimelength());
        bean.setCreateTime(resultBean.getCreatetime());
        bean.setMsgType(resultBean.getMessagetype());
        bean.setUnread(resultBean.getState());
        bean.setReceiver(resultBean.getRecipient());
        bean.setSendStatus(1);
        if (TextUtils.equals(username, resultBean.getUsername())) {
            bean.setDirect(0);
        } else {
            bean.setDirect(1);
        }
        return bean;
    }

    private void refreshItemById(long id) {
        for (int i = dataList.size() - 1; i >= 0; i--) {
            if (dataList.get(i).getId() == id) {
                msgListAdapter.notifyItemChanged(i);
                recyclerViewAdapter.notifyDataSetChanged();
                return;
            }
        }
    }

    private void init() {
        msgListAdapter = new MsgListAdapter(this, dataList);
        recyclerViewAdapter = new LRecyclerViewAdapter(msgListAdapter);
        lrvChat.setRefreshHeader(new ArrowRefreshHeader(this));
        lrvChat.setAdapter(recyclerViewAdapter);
        msgListAdapter.setSendFailClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = (int) v.getTag();
                ChatMsgBean bean = dataList.get(position);
                bean.setSendStatus(0);
                msgListAdapter.notifyItemChanged(position);
                recyclerViewAdapter.notifyDataSetChanged();
                model.sendMsg(bean.getId(), bean);//重发
            }
        });
        msgListAdapter.setLlContentClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = (int) v.getTag(R.id.indexTag);
                ChatMsgBean bean = dataList.get(position);
                if (bean.getDirect() == 1) {//接收
                    bean.setUnread(1);
                    msgListAdapter.notifyItemChanged(position);
                    recyclerViewAdapter.notifyDataSetChanged();
                    msgDao.update(bean);//更新消息阅读状态
                }
                MsgListAdapter.ViewHolder viewHolder = (MsgListAdapter.ViewHolder) v.getTag(R.id.viewHolder);
                AppUtil.showLog(viewHolder);
            }
        });
//        DividerDecoration divider = new DividerDecoration.Builder(this)
//                .setHeight(R.dimen.default_divider_height)
//                .setPadding(R.dimen.default_divider_padding)
//                .setColorResource(R.color.color_view_line)
//                .build();
        lrvChat.setHasFixedSize(true);
//        lrvChat.addItemDecoration(divider);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
//        layoutManager.setStackFromEnd(true);
        lrvChat.setLayoutManager(layoutManager);

//        lrvChat.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
//        lrvChat.setArrowImageView(R.drawable.ic_pulltorefresh_arrow);
//        recyclerViewAdapter.addHeaderView(new SampleHeader(this));

        lrvChat.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (dataList.size() % pageSize == 0) {
                    page++;
                    getDataFromDb();
                } else {
                    lrvChat.setPullRefreshEnabled(false);
                    AppUtil.showToast(ChatActivity.this, "没有更多数据了");
                    lrvChat.refreshComplete(pageSize);
                }
            }
        });
    }

    private void getDataFromDb() {
        List<ChatMsgBean> list = msgDao.queryBuilder()
                .where(ChatMsgBeanDao.Properties.Sender.eq(username), ChatMsgBeanDao.Properties.Receiver.eq(receiver))
                .orderDesc(ChatMsgBeanDao.Properties.CreateTime).offset(page * pageSize).limit(pageSize).list();
        Collections.reverse(list);
        if (list != null && list.size() > 0) {
            dataList.clear();
            AppUtil.showLog(JSON.toJSONString(list));
            dataList.addAll(0, list);
            msgListAdapter.notifyDataSetChanged();
            recyclerViewAdapter.notifyDataSetChanged();
            if (page == 0) {
                lrvChat.scrollToPosition(dataList.size());
            }
        }/* else {
            if (isFirst) {
                isFirst = false;
                model.getMsgList(page, 20);
            }
        }*/
        lrvChat.refreshComplete(pageSize);
//        List list = new ArrayList();
//        for (int i = 0; i < 10; i++) {
//            if (i % 2 == 0) {
//                list.add(new MultipleItem(MultipleItem.VOICE_RECEIVE));
//            } else {
//                list.add(new MultipleItem(MultipleItem.VOICE_SEND));
//            }
//        }
//        msgListAdapter.addAll(list);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        EventBusManager.post(new EventBusBean.Builder().id(Constant.EventBusId.START_CAE_AND_AIUI).build());
        model.removeListener();
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
    }
}
